package cn.itlight.system.service.impl;

import cn.itlight.org.domain.Department;
import cn.itlight.system.domain.Menu;
import cn.itlight.system.mapper.MenuMapper;
import cn.itlight.system.service.IMenuService;
import cn.itlight.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tomliu
 * @since 2022-07-11
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<Menu> tree() {
        // 1.一次性查询出全部数据
        List<Menu> menus = menuMapper.loadAll();

        // 2.创建一个集合对象，用于放最终排列完成的树数据
        List<Menu> menuTree = new ArrayList<Menu>();

        // 3.将集合数据换转为map，消除时间复杂度问题
        // Map<Long, Department> deptMap = deptTree.stream().collect(Collectors.toMap(Department::getId, item -> item));
        HashMap<Long, Menu> menuMap = new HashMap<>();
        for (Menu menu : menus) {
            menuMap.put(menu.getId(), menu);
        }

        for (Menu menu : menus){
            if (menu.getParentId() ==null){
                menuTree.add(menu);
            } else {
                // 从map集合中获取到父对象，将自己添加到父对象的children集合中
                Menu menu1 = menuMap.get(menu.getParentId());
                if (menu1 != null){
                    menu1.getChildren().add(menu);
                }
            }

        }
        return menuTree;
    }
}
